package com.lxs.spring6.boot3.extend;

import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor;
import org.springframework.stereotype.Component;

/**
 * 该接口继承了BeanPostProcess接口，区别如下：
 * BeanPostProcess接口只在bean的初始化阶段进行扩展（注入spring上下文前后），而InstantiationAwareBeanPostProcessor接口在此基础上增加了3个方法，把可扩展的范围增加了实例化阶段和属性注入阶段。
 */
@Component
public class MyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {
    @Override
    public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException {
//        System.err.println("--------------------------------------");
        // 1.实例化bean之前，相当于new这个bean之前
        if ("myBeanNameAware".equals(beanName)) {
            System.err.println("1.postProcessBeforeInstantiation-"+beanName+"：实例化bean之前，相当于new这个bean之前");
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInstantiation(beanClass, beanName);
    }

    @Override
    public boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException {
        // 2.实例化bean之后，相当于new这个bean之后
        if ("myBeanNameAware".equals(beanName)) {
            System.err.println("2.postProcessAfterInstantiation-" + beanName + "：实例化bean之后，相当于new这个bean之后");
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessAfterInstantiation(bean, beanName);
    }

    @Override
    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) throws BeansException {
        // 3.bean已经实例化完成，在属性注入时阶段触发，@Autowired,@Resource等注解原理基于此方法实现
        if ("myBeanNameAware".equals(beanName)) {
            System.err.println("3.postProcessProperties-"+beanName+"：bean已经实例化完成，在属性注入时阶段触发，@Autowired,@Resource等注解原理基于此方法实现");
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessProperties(pvs, bean, beanName);
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        // 4.初始化bean之前，相当于把bean注入spring上下文之前
        if ("myBeanNameAware".equals(beanName)) {
            System.err.println("4.postProcessBeforeInitialization-" + beanName + "：初始化bean之前，相当于把bean注入spring上下文之前");
        }
        return InstantiationAwareBeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 5.初始化bean之后，相当于把bean注入spring上下文之后，注入多次，则被调用多次
        if ("myBeanNameAware".equals(beanName)) {
            System.err.println("5.postProcessAfterInitialization-" + beanName + "：初始化bean之后，相当于把bean注入spring上下文之后");
        }
//        System.err.println("--------------------------------------");
        return InstantiationAwareBeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
